package com.web.activiti.service.Impl;

import com.github.pagehelper.PageHelper;
import com.web.activiti.mapper.BaoXiaoBillMapper;
import com.web.activiti.pojo.BaoXiaoBill;
import com.web.activiti.pojo.BaoXiaoBillExample;
import com.web.activiti.pojo.Employee;
import com.web.activiti.pojo.Leavebill;
import com.web.activiti.service.ReimbFlowService;
import com.web.activiti.utils.Contants;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
public class ReimbFlowServiceImpl  implements ReimbFlowService {
    @Autowired
    private RepositoryService repositoryService;  //流程定义
    @Autowired
    private RuntimeService runtimeService;        //流程实例
    @Autowired
    private TaskService taskService;              //活动任务节点
    @Autowired
    private BaoXiaoBillMapper baoxiaoMapper;       //报销映射
    @Autowired
    private HistoryService historyService;


    /**
     * 保存报销单
     * @param baoXiaoBill
     * @param employee
     */
    @Override
    public void saveStartProcess (BaoXiaoBill baoXiaoBill , Employee employee) {
        System.out.println("正在保存。。。");
        //1.保存请假单到数据库
        baoXiaoBill.setCreatdate(new Date());
        baoXiaoBill.setState(1);
        baoXiaoBill.setUserId(employee.getId());
        baoxiaoMapper.insert(baoXiaoBill);

        //2.启动流程实例
        String key= Contants.BAOXIAO_KEY;
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", employee.getName());
        String BUSSINESS_KEY=Contants.BAOXIAO_KEY+"." +baoXiaoBill.getId();
        System.out.println(baoXiaoBill.getId());
        runtimeService.startProcessInstanceByKey(key,BUSSINESS_KEY,map);
    }

    @Override
    public List<Task> findTaskListByUserId (String name) {
        System.out.println("查询列表");
        return taskService.createTaskQuery().taskAssignee(name).list();
    }

    /**
     * 通过id查看该请假条的批注
     * @param taskId
     * @return
     */
    @Override
    public List<Comment> findCommentList (String taskId) {
        System.out.println(taskId);
        Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
        List<Comment> comments = taskService.getProcessInstanceComments(task.getProcessInstanceId());
        return comments;
    }


    @Override
    public BaoXiaoBill findBillByTask (String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().
                processInstanceId(task.getProcessInstanceId())
                .singleResult();
        String businessKey = pi.getBusinessKey();
        System.out.println(businessKey);
        String id = businessKey.split("\\.")[1];
        BaoXiaoBill baoxiao = baoxiaoMapper.selectByPrimaryKey(Long.parseLong(id));
        return baoxiao;
    }


    @Override
    public void saveSubmitTask (long id , String taskId , BigDecimal money, String come, String comment , String name) {
        //加批注
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        String processInstanceId = task.getProcessInstanceId();
        //加当前任务的审核人
        Authentication.setAuthenticatedUserId(name);
        taskService.addComment(taskId , processInstanceId , comment);
        //流程要结束，往前推进
        HashMap<String, Object> map = new HashMap<>();
        System.out.println("come="+come);
        map.put("message", come);
        String message = (String) map.get("message");
        System.out.println("message = " + message);
        taskService.complete(taskId,map);
        //如果流程实例结束，修改业务表的状态
        ProcessInstance pi = runtimeService.createProcessInstanceQuery()
                .processInstanceId(task.getProcessInstanceId()).singleResult();
        System.out.println("pi = " + pi);
        if (pi == null) {
            BaoXiaoBill baoXiaoBill = baoxiaoMapper.selectByPrimaryKey(id);
            baoXiaoBill.setState(2);
            baoxiaoMapper.updateByPrimaryKey(baoXiaoBill);
        }
    }

    /**使用部署对象ID和资源图片名称，获取图片的输入流*/
    @Override
    public InputStream findImageInputStream(String deploymentId, String imageName) {
        return repositoryService.getResourceAsStream(deploymentId, imageName);
    }

    @Override
    public ProcessDefinition findProcessDefinitionByTaskId (String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessDefinitionId();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processInstanceId).singleResult();
        return processDefinition;
    }

    @Override
    public Map<String, Object> findCoordingByTask(String taskId) {
        //存放坐标
        Map<String, Object> map = new HashMap<String,Object>();
        //使用任务ID，查询任务对象
        Task task = taskService.createTaskQuery()//
                .taskId(taskId)//使用任务ID查询
                .singleResult();
        System.out.println("task"+task==null);
        //获取流程定义的ID
        String processDefinitionId = task.getProcessDefinitionId();
        System.out.println("processDefinitionId = " + processDefinitionId);
        //获取流程定义的实体对象（对应.bpmn文件中的数据）
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity)repositoryService.getProcessDefinition(processDefinitionId);
        //流程实例ID
        String processInstanceId = task.getProcessInstanceId();
        //使用流程实例ID，查询正在执行的执行对象表，获取当前活动对应的流程实例对象
        ProcessInstance pi = runtimeService.createProcessInstanceQuery()//创建流程实例查询
                .processInstanceId(processInstanceId)//使用流程实例ID查询
                .singleResult();
        //获取当前活动的ID
        String activityId = pi.getActivityId();
        System.out.println("activityId = " + activityId);
        //获取当前活动对象
        ActivityImpl activityImpl = processDefinitionEntity.findActivity(activityId);//活动ID
        //获取坐标
        map.put("x", activityImpl.getX());
        map.put("y", activityImpl.getY());
        map.put("width", activityImpl.getWidth());
        map.put("height", activityImpl.getHeight());
        return map;
    }

    @Override
    public List<BaoXiaoBill> findMyBaoXiaoBillByUser (Employee employee,boolean isOk,Integer pageNum) {
        BaoXiaoBillExample example=new BaoXiaoBillExample();
        BaoXiaoBillExample.Criteria criteria=example.createCriteria();
        criteria.andUserIdEqualTo(employee.getId());
        if (isOk) {
            PageHelper.startPage(pageNum , 7);
        }
        List<BaoXiaoBill> baoxiaos = baoxiaoMapper.selectByExample(example);
        return baoxiaos;
    }

    @Override
    public void deleteBillById (String id) {
        int i = baoxiaoMapper.deleteByPrimaryKey(Long.parseLong(id));
        if (i>0){
            System.out.println("删除。。。");
        }
    }

    @Override
    public Task findTaskByBussinessKey(String bUSSINESS_KEY) {
        Task task = this.taskService.createTaskQuery().processInstanceBusinessKey(bUSSINESS_KEY).singleResult();
        return task;
    }

    @Override
    public List<Comment> findCommentByBaoxiaoBillId(long id) {
        String bussiness_key = Contants.BAOXIAO_KEY +"."+id;
        HistoricProcessInstance pi = this.historyService.createHistoricProcessInstanceQuery()
                .processInstanceBusinessKey(bussiness_key).singleResult();
        List<Comment> commentList = this.taskService.getProcessInstanceComments(pi.getId());
        return commentList;
    }

    @Override
    public BaoXiaoBill findBillById (long id) {
        return baoxiaoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void delDeploymentById (String deploymentId) {
        repositoryService.deleteDeployment(deploymentId, true);
    }

    @Override
    public List<String> findOutComeListByTaskId(String taskId) {
        //返回存放连线的名称集合
        List<String> list = new ArrayList<String>();
        //1:使用任务ID，查询任务对象
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //2：获取流程定义ID
        String processDefinitionId = task.getProcessDefinitionId();
        //3：查询ProcessDefinitionEntiy对象
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processDefinitionId);
        //使用任务对象Task获取流程实例ID
        String processInstanceId = task.getProcessInstanceId();
        //使用流程实例ID，查询正在执行的执行对象表，返回流程实例对象
        ProcessInstance pi = runtimeService.createProcessInstanceQuery()//
                .processInstanceId(processInstanceId)//使用流程实例ID查询
                .singleResult();
        //获取当前活动的id
        String activityId = pi.getActivityId();
        //4：获取当前的活动
        ActivityImpl activityImpl = processDefinitionEntity.findActivity(activityId);
        //5：获取当前活动完成之后连线的名称
        List<PvmTransition> pvmList = activityImpl.getOutgoingTransitions();
        if(pvmList!=null && pvmList.size()>0){
            for(PvmTransition pvm:pvmList){
                String name = (String) pvm.getProperty("name");
                if(StringUtils.isNotBlank(name)){
                    list.add(name);
                } else{
                    list.add("提交");
                }
            }
        }

        return list;
    }
}
